package com.bosssoft.trainee.nontax.controller;


import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.po.Role;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.entity.po.UserRole;
import com.bosssoft.trainee.nontax.service.IRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Resource
    private IRoleService roleService;

    @PostMapping
    public Result<?> save(@RequestBody Role role) {
        if (exists(role))  return Result.error("-1", "该角色已经存在！");
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Role role) {
        roleService.updateById(role);
        return Result.success();
    }

    // 改变权限接口
    @PutMapping("/changePermission")
    public Result<?> changePermission(@RequestBody Role role) {
        roleService.changePermission(role);
        // 判断当前登录的用户角色是否包含了当前操作行的角色id，如果包含，则返回true，需要重新登录。
        Result result = getUser();
        if (result.getCode().equals("0")) {
            User user = (User) result.getData();
            List<UserRole> userRoles = roleService.getUserRoleByUserId(user.getId());
            if (userRoles.stream().anyMatch(userRole -> userRole.getRoleId().equals(role.getId()))) {
                return Result.success(true);
            } else {
                // 如果不包含，则返回false，不需要重新登录。
                return Result.success(false);
            }
        } else {
            return result;
        }


    }

    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        roleService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(roleService.getById(id));
    }

    @GetMapping("/all")
    public Result<?> all() {
        return Result.success(roleService.list());
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        return roleService.findPage(pageNum, pageSize, search);
    }

    private boolean exists(Role role) {
        List<Role> roles = (List<Role>) all().getData();
        for (Role r : roles) {
            if (r.getId().equals(role.getId())) return true;
        }
        return false;
    }
}
